﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace MyMainSite2.Library.Tests
{
	public class TestBase<TDBContext, TTestClass> : IDisposable
				 where TDBContext: DbContext, new()
	{
		#region Properties

		public TDBContext DbContext
		{
			get { return _dbContext; }
			set { _dbContext = value; }
		}
		private TDBContext _dbContext = new TDBContext();

		#endregion

		#region Public Methods

		public void Dispose()
		{
			this.Dispose(true);
		}

		protected virtual void Dispose(bool all)
		{
			if (all)
			{
				this.DbContext.Dispose();
			}
		}

		#endregion

		#region Protected Methods

		protected bool HasMethodGotAttribute(string methodName, Type[] types, Type attributeType)
		{
			var type = typeof(TTestClass);

			var methodInfo = type.GetMethod(methodName, types);

			var attributes = methodInfo.GetCustomAttributes(attributeType, true);

			var hasAttribute = attributes.Length > 0;
			return hasAttribute;
		}

		protected bool HasMethodGotAuthorizeAttribute(string methodName)
		{
			return this.HasMethodGotAuthorizeAttribute(methodName, new Type[] { });
		}

		protected bool HasMethodGotAuthorizeAttribute(string methodName, Type[] types)
		{
			return this.HasMethodGotAttribute(methodName, types, typeof(AuthorizeAttribute));
		}

		protected bool HasMethodGotHttpPostAttribute(string methodName)
		{
			return this.HasMethodGotHttpPostAttribute(methodName, new Type[] { });
		}

		protected bool HasMethodGotHttpPostAttribute(string methodName, Type[] types)
		{
			return this.HasMethodGotAttribute(methodName, types, typeof(HttpPostAttribute));
		}

		protected bool HasMethodGotRole(string methodName, string role)
		{
			return this.HasMethodGotRole(methodName, new Type[] { }, role);
		}

		protected bool HasMethodGotRole(string methodName, Type[] types, string role)
		{
			bool result = false;

			var type = typeof(TTestClass);

			var methodInfo = type.GetMethod(methodName, types);

			var attributes = methodInfo.GetCustomAttributes(typeof(AuthorizeAttribute), true);

			if (attributes.Length > 0)
			{
				var attr = (AuthorizeAttribute)attributes[0];

				result = attr.Roles.Contains(role);
			}

			return result;
		}

		#endregion
	}
}
